package com.davinci.freemarket.businessLayer.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.davinci.freemarket.businessLayer.utils.WebParamsStandarized;
import com.davinci.freemarket.dataAccessLayer.accessdata.user.UserDAO;
import com.davinci.freemarket.dataModelLayer.model.UserModel;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/servlet/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		try {	    
			UserModel user = new UserModel();
			user.setEmail(request.getParameter(WebParamsStandarized.PARAMETER_LOGIN_MAIL));
			user.setPass(request.getParameter(WebParamsStandarized.PARAMETER_LOGIN_PASSWORD));
			
			UserDAO userdao = new UserDAO();
			
			try {
				user = userdao.login(user);
			} catch (SQLException e) {
				e.printStackTrace();
			}

			if (user.isUserValid()) {
				HttpSession session = request.getSession(true);
				session.setAttribute("currentSessionUser",user); 
//				response.sendRedirect("userLogged.jsp"); //logged-in page      		
				response.sendRedirect("../Main.jsp");
			} else {
				response.sendRedirect("../login.jsp?error=Login Incorrecto"); //error page 
			}
			

		} 
		catch (Throwable theException) {
			System.out.println(theException); 
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
